package myStack;
import java.util.Arrays;

import java.util.Stack;

public class MyStack implements IStackOperation{
    /**
     * 栈的模拟实现：
     * 栈的特征：后进先出
     * 栈的底层就是由一个数组构成*/

    /*使用数组存储数据，再加上一个计数器，便于出栈，入栈等操作*/
    private int[] elem;
    private int usedSize;
    private static final int DEFAULT_CAPACITY = 10;

    /*提供两种构造方法：1：开辟默认大小的空间 2：开辟指定大小的空间*/
    public MyStack() {
        elem = new int[DEFAULT_CAPACITY];
    }
    public MyStack(int capacity) {
        try {
            if (capacity <= 0) {
                //抛异常
                throw new IIllegalException("构造参数非法，已执行默认构造！ 非法参数："+capacity);
            } else {
                this.elem = new int[capacity];
            }
        } catch(IIllegalException e) {
            capacity = DEFAULT_CAPACITY;
        }
    }
    //入栈
    @Override
    public void push(int val) {
        //满栈-》二倍扩容
        if(checkCapacity()) {
            this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
        }
        this.elem[this.usedSize++] = val;
    }

    @Override
    public int pop() {
        try{
            if(empty()) {
                throw new IIllegalException("栈为空，无法删除！");
            } else {
                int old = this.elem[--this.usedSize];
                return old;
            }
        } catch(IIllegalException e) {
            System.out.println("已跳过该操作！");
            return -404;
        }
    }

    @Override
    public int peek() {
        return this.elem[this.usedSize-1];
    }

    @Override
    public boolean empty() {
        return this.usedSize==0;
    }

    public int size() {
        return this.usedSize;
    }

    @Override
    public boolean checkCapacity() {
        return this.usedSize==this.elem.length;
    }

}
